package cn.sytton.taffe.framework.mybatis;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Sql中文排序处理工具类
 *
 * @author skyrock
 */
@Component
public class SortHelper {

    private static boolean isMysql;

    //todo 不要取yml
    @Value("${spring.datasource.db.master.driverClassName:mysql}")
    public void setDriver(String driver) {
        isMysql = driver.contains("mysql");
    }

    public static String convertGbk(String sort) {
        if (isMysql && StringUtils.hasText(sort)) {
            Pattern pattern = Pattern.compile("[a-zA-Z0-9]+\\(gbk\\)", Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(sort);
            StringBuffer sb = new StringBuffer();
            while (matcher.find()) {
                String txt = matcher.group(0);
                String field = txt.substring(0, txt.indexOf("("));
                String convertFiled = "CONVERT(" + field + " USING gbk)";
                matcher.appendReplacement(sb, convertFiled);
            }
            matcher.appendTail(sb);
            return sb.toString();
        } else {
            return sort;
        }
    }

    public static void main(String[] arg) {
        System.out.println( SortHelper.convertGbk("user(gbk), code(GBK) desc, loginName(gbk) asc") );
        System.out.println( SortHelper.convertGbk("user") );
        System.out.println( SortHelper.convertGbk("") );
    }
}
